package cn.yqn.service.impl;

import cn.yqn.domain.MovieTicket;
import cn.yqn.domain.User;
import cn.yqn.feign.MovieFeignService;
import cn.yqn.mapper.UserMapper;
import cn.yqn.result.JsonResult;
import cn.yqn.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private MovieFeignService movieFeignService;

    // 查询所有
    @Override
    public JsonResult movies() {
        return movieFeignService.list();
    }

    @Override
    public JsonResult buy(Long movieId) {
        // 判断电影服务那边是否成功，如果失败，那么直接返回JsonResult
        JsonResult jsonResult = movieFeignService.buy(1L, movieId);
        if (!jsonResult.isSuccess()){
            return jsonResult;
        }
        // 如果电影服务那边成功，那么我们直接扣减余额
        User user = selectById(1L);
        BigDecimal bigDecimal = JsonResult.getBigDecimal(jsonResult.getData());
        BigDecimal newDecimal = user.getBalance().subtract(bigDecimal);
        user.setBalance(newDecimal);
        updateById(user);
        return JsonResult.success();
    }

    @Override
    public JsonResult watch(Long movieId) {
        return movieFeignService.watch(1L, movieId);
    }

    @Override
    public boolean insert(User entity) {

        super.insert(entity);

        // 1.查询所有电影票 @TODO 做的更好的话，不要用list，专门再来一个接口，查询可以赠送的电影票
        JsonResult jsonResult = movieFeignService.list();
        // 如果是Object 需要转换成list对象集合，需要像下面这样转，用强转要报错
        List<MovieTicket> movieTickets = JSONObject.parseArray(JSONObject.toJSONString(jsonResult.getData()), MovieTicket.class);
        // 得到随机数，随便拿一张电影票，做的更好的话，不要用list，专门再来一个接口，查询可以赠送的电影票
        int random = (int)(Math.random() * movieTickets.size());
        MovieTicket movieTicket = movieTickets.get(random);
        // 给用户送电影票
        movieFeignService.buy(entity.getId(), movieTicket.getId());

        return true;
    }
}
